package com.leetcode.list;

import java.util.ArrayList;
import java.util.Collections;

public class MergeInterval {
    private static class Interval{
        private int start;
        private int end;

        public Interval() {
        }

        public Interval(int start, int end) {
            this.start = start;
            this.end = end;
        }

        public int getStart() {
            return start;
        }

        public void setStart(int start) {
            this.start = start;
        }

        public int getEnd() {
            return end;
        }

        public void setEnd(int end) {
            this.end = end;
        }
    }

    public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
        Collections.sort(intervals, (x, y) -> x.getStart() - y.getStart());
        ArrayList<Interval> res = new ArrayList<>();
        int index = -1;
        for (Interval interval : intervals) {
            if(index == - 1 || interval.getStart() > res.get(index).getEnd()){
                res.add(interval);
                index++;
            }else{
                int end = Math.max(res.get(index).getEnd(), interval.getEnd());
                res.get(index).setEnd(end);
            }
        }
        return res;
    }
}

